package com.eonmind.gateway.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class LoggingFilter extends AbstractGatewayFilterFactory<LoggingFilter.Config> {


    public LoggingFilter() {
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            // 打印请求信息
            ServerHttpRequest request = exchange.getRequest();
            log.info("-------- Request Log --------");
            log.info("URI       : {}", request.getURI());
            log.info("Method    : {}", request.getMethod());
            log.info("Headers   : {}", request.getHeaders());
            log.info("QueryParams : {}", request.getQueryParams());

            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                // 打印响应信息
                ServerHttpResponse response = exchange.getResponse();
                log.info("-------- Response Log --------");
                log.info("Status Code : {}", response.getStatusCode());
            }));
        };
    }

    public static class Config {
        // 这里可以添加配置类的参数（如果需要的话）
    }
}
